'''
Created on Oct 7, 2012

@author: jake
'''
import urllib
import re
from lib.aj.snapvideo import VideoWeed
from lib.aj.common.DataObjects import VIDEO_QUAL_SD

extensions = ['.m4v', '.3gp', '.nsv', '.ts', '.ty', '.strm', '.rm', '.rmvb', '.m3u', '.ifo', '.mov', '.qt', '.divx', '.xvid', '.bivx', '.vob', '.nrg', '.img', '.iso', '.pva', '.wmv', '.asf', '.asx', '.ogm', '.m2v', '.avi', '.bin', '.dat', '.dvr-ms', '.mpg', '.mpeg', '.mp4', '.mkv', '.avc', '.vp3', '.svq3', '.nuv', '.viv', '.dv', '.fli', '.flv', '.rar', '.001', '.wpl', '.zip']

class VideoFromHost:
    def hasVideoExtensionInURL(self, url):
        if self.searchSpecifiedVideoExtension(url) is True:
            return True
        else:
            return False
    
    
    def searchSpecifiedVideoExtension(self, url):
        url = str(url)
        
        for ext in extensions:
            ind = url.find(ext)
            if ind is not -1:
                print "Found: " + ext
                return True
        
        return False
    
    def getHostFromURL(self, url):
        url = str(url)
        url = url.lower()
        
        if url.find('videoweed') is not -1:
            return "VIDEOWEED"
        else:
            return None
        
    def getVideoID(self, url, pattern):
        reg = re.compile(pattern)
        findID = reg.search(str(url))
        return findID.group()
        
    def getVideoURL(self, url):
        if self.hasVideoExtensionInURL(url) is False:
            host = self.getHostFromURL(url)
            
            if host is None:
                print "[AnimeFreak] None Host"
                return "[AnimeFreak]: " + url
                
            elif host is "VIDEOWEED":
                video_id = self.getVideoID(url + '&', "v=.*?&")
                video_id = video_id.replace("&","")
                video_id = video_id.replace("v=","")
                video_info = VideoWeed.retrieveVideoInfo(video_id)
                print '[AnimeFreak] Getting video from VideoWeed'
                
                reg = re.compile("^http.*\|")
                findID = reg.search(str(video_info.get_video_link(VIDEO_QUAL_SD)))
                url = findID.group()
                url = url.replace("|","")
                
                print url
                return url
            
        else:
            return url
        

#VideoFromHost().getVideoURL("http://embed.videoweed.com/embed.php?logo=af&v=vx7nowh4u9zp7&width=550&height=412")